package com.zhiyume.controller;

import com.zhiyume.Appliaction;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.util.*;

/**
 * Created by wang on 18/7/7.
 */
@Controller
@RequestMapping("/monitor")
public class MonitorController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(MonitorController.class);

    @Value("${custom.jvm.path}")
    private String dataPath;

    @Value("${custom.jvm.num}")
    private String dataNum;

    @RequestMapping("/mgr")
    public ModelAndView mgr(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("page/monitor/mgr");
        return mv;
    }

    @RequestMapping("/data.json")
    @ResponseBody
    public Map data(){
        Map data = new HashMap();
        List<String> zyzl1 = new ArrayList<String>();
        List<String> timeList = new ArrayList<String>();
        List<String> diff = new ArrayList<String>();
        List<String> diff2 = new ArrayList<String>();
        String[] times = null;
        Map<String,String> orderBy = new HashMap<String,String>();
        BufferedReader br = null;

        try { // 防止文件建立或读取失败，用catch捕捉错误并打印，也可以throw

                /* 读入TXT文件 */
            String pathname = dataPath; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
            String num = dataNum;
            File filename = new File(pathname); // 要读取以上路径的input。txt文件


            if(filename.isDirectory()){
                File[] files = filename.listFiles();
                List<File> filesRec = null;
                //按num来获取最新的
                int fileNum =Integer.parseInt(num);

                if(files!=null){

                    if(files.length<=fileNum) {
                        filesRec = Arrays.asList(files);
                    }else{
                        filesRec = Arrays.asList(files).subList(files.length-1-fileNum,files.length-1);
                    }

                    for(File file:filesRec){

                        String time = file.getName();
                        logger.info("【获取文件名称】"+time);

                        String key = "";
                        if(time.endsWith("dump.log")){
                            if(time.contains("-")){
                                String[] timeSplit = time.split(System.getProperty("file.separator"));
                                String timeStr = timeSplit[timeSplit.length-1];
                                timeList.add(timeStr.split("-")[0]);
                                key = timeStr.split("-")[0];
                            }

                            br = new BufferedReader(new InputStreamReader(
                                    new FileInputStream(file),"utf-8"));
                            // 建立一个对象，它把文件内容转成计算机能读懂的语言
                            String line = br.readLine();
                            while (line != null) {
                                line = line.trim();
                                if(line.contains("java") && line.contains("zyzl1")){

                                    String[] zyzl = line.split("\\s+");
                                    if(StringUtils.isNoneBlank(key)) orderBy.put(key,zyzl[4]);
                                }
                                line = br.readLine();
                            }


                        }

                    }
                }

            }

        } catch (RuntimeException e) {
            throw e;

        } catch (Exception e){
            e.printStackTrace();

        }finally {
            try {
                if(br!=null)
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        times = timeList.toArray(new String[timeList.size()]);
        List<String> yAxis = new ArrayList<>();

        Arrays.sort(times,new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for(String key:times){
            zyzl1.add(orderBy.get(key));
            yAxis.add(key.substring(4));
        }
        data.put("list",zyzl1);

        data.put("times",yAxis);
        int b = Integer.parseInt(zyzl1.get(0));
        for(int a=0;a<zyzl1.size();a++){
            if(a == 0){
                diff.add("0");
                diff2.add("0");
            }else{

                int b1 = Integer.parseInt(zyzl1.get(a));
                int b2 = Integer.parseInt(zyzl1.get(a-1));
                diff.add(String.valueOf(b1-b2));
                diff2.add(String.valueOf(b1-b));
            }
        }
        data.put("diff",diff);
        data.put("diff2",diff2);
        return data;
    }
}
